<template>
    <el-row>
        <el-col :span="24">
            <el-card shadow="never">
                <template #header>
                    <h3>用户管理列表</h3>
                </template>
                <div>
                    <el-row>
                        <el-col :span="24">
                            <div class="account-table-toolbar">
                                <el-input v-model="filterVal" placeholder="按昵称、用户名搜索">
                                    <template #append>
                                        <el-button icon="el-icon-search" @click="doSearch"></el-button>
                                    </template>
                                </el-input>
                                <el-button-group>
                                    <el-button type="success" icon="el-icon-plus" @click="addAccount">添加用户</el-button>
                                    <el-button type="success" icon="el-icon-circle-check" @click="batchGrant">批量授权
                                    </el-button>
                                    <el-button type="success" icon="el-icon-circle-close" @click="revokeAll">回收全部权限</el-button>
                                </el-button-group>
                            </div>
                        </el-col>
                    </el-row>

                    <el-table :data="accountTableData"
                              ref="accountTable"
                              @selection-change="handleSelectRows"
                              :cell-style="{height: '20px', padding: '5px 0'}">
                        <!--                        <el-table-column type="expand">
                                                    <template #default="props">
                                                        <el-form class="favor-expand-row" label-position="right" label-width="90px">
                                                            <el-form-item label="资源名称">
                                                                <span>{{ props.row.name }}</span>
                                                            </el-form-item>
                                                            <el-form-item label="资源URL">
                                                                <span>{{ props.row.url }}</span>
                                                            </el-form-item>
                                                            <el-form-item label="所属类别">
                                                                <el-tag size="medium" type="warning">
                                                                    {{ props.row.catalogName }}
                                                                </el-tag>
                                                            </el-form-item>
                                                            <el-form-item label="描述">
                                                                <p style="word-break: break-word; line-height: 25px; padding: 8px 0 17px 0;">
                                                                    {{ props.row.description }}
                                                                </p>
                                                            </el-form-item>
                                                        </el-form>
                                                    </template>
                                                </el-table-column>-->
                        <el-table-column type="selection" width="50"/>
                        <el-table-column type="index" width="40"/>
                        <el-table-column prop="nickName" label="用户昵称"/>
                        <el-table-column prop="username" label="用户名"/>
                        <el-table-column label="性别" width="60">
                            <template #default="scope">
                                <el-tag v-if="scope.row.gender === 1" size="mini" type="success">女</el-tag>
                                <el-tag v-else-if="scope.row.gender === 2" size="mini">男</el-tag>
                                <el-tag v-else size="mini" type="info">未知</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="角色">
                            <template #default="scope">
                                <el-tag v-for="r in scope.row.roles" style="margin-right: 5px"
                                        size="mini"
                                        type="warning">{{ r.name }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <!--                        <el-table-column prop="email" label="邮箱号"/>-->
                        <el-table-column prop="createDate" :formatter="dataFormat" width="160" label="创建时间"/>
                        <el-table-column fixed="right" align="center" label="操作" width="160">
                            <template #default="scope">
                                <el-button @click="modifyAccount(scope.row)" type="primary" size="mini">修改</el-button>
                                <el-button @click.prevent="delAccount(scope.$index, accountTableData, scope.row.id)"
                                           type="danger"
                                           size="mini">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                        style="text-align: right;padding: 10px 0 30px 0;"
                        background
                        layout="total, sizes, prev, pager, next"
                        :page-sizes="[10, 15, 20, 30, 50]"
                        v-model:currentPage="accountPage.curPageNo"
                        v-model:page-size="accountPage.pageSize"
                        :total="accountPage.total"
                        @size-change="handleSizeChange"
                        @current-change="handlePageChange">
                    </el-pagination>
                </div>
            </el-card>
        </el-col>
        <account-form v-model:show="accForm.show"
                      :opt="accForm.event"
                      :datas="accForm.data"
                      @finishMethod="loadPageData"/>
        <grant-dialog v-model:show="grantObj.show"
                      :datas="grantObj.users"
                      @finished="loadPageData"/>

    </el-row>
</template>

<script>
import AccountForm from "@/views/system/account/AccountForm"
import GrantDialog from "@/views/system/account/GrantDialog"
import accountReq from "@/services/account/request"

export default {
    name: "Account",
    components: {GrantDialog, AccountForm},
    methods: {
        addAccount() {
            this.accForm.data = {}
            this.accForm.event = "ADD"
            this.accForm.show = true
        },
        modifyAccount(row) {
            // 浅拷贝：如果修改了数据，但是没有提交，页面就不能与后台同步
            // this.accForm.data = row
            // 深拷贝
            this.accForm.data = JSON.parse(JSON.stringify(row))
            this.accForm.event = "EDIT"
            this.accForm.show = true
        },
        delAccount(index, rows, id) {
            this.$confirm("是否永久删除该用户？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(async () => {
                let r = await accountReq.delete({}, [id])
                if (r.code === 0) {
                    this.$message.success("操作成功");
                    rows.splice(index, 1);
                } else {
                    this.$message.error(r.msg);
                }
            }).catch(err => {
            });
        },
        handleSizeChange(sz) {
            this.loadPageData(this.accountPage.curPageNo, sz)
        },
        handlePageChange(v) {
            this.loadPageData(v, this.accountPage.pageSize)
        },
        initAccountPage() {
            this.accountPage.curPageNo = 1
            this.accountPage.pageSize = 10
            this.accountPage.total = 0
        },
        dataFormat: function (row, column) {
            let data = row[column.property]
            if (data === null) return ''
            let d = new Date(data)
            return d.getFullYear() + '-' + (d.getMonth() + 1) + '-'
                + d.getDate() + ' ' + d.getHours() + ':'
                + d.getMinutes() + ':' + d.getSeconds()
        },
        doSearch() {
            this.loadPageData(this.accountPage.curPageNo, this.accountPage.pageSize, this.filterVal)
        },
        handleSelectRows(selection) {
            this.grantObj.users = selection
        },
        batchGrant() {
            if (!this.grantObj.users || this.grantObj.users.length < 1) {
                this.$message.warning('请先选择用户！')
                return
            }
            this.grantObj.show = true
        },
        revokeAll() {
            if (!this.grantObj.users || this.grantObj.users.length < 1) {
                this.$message.warning('请先选择用户！')
                return
            }
            let n = this.grantObj.users.length
            this.$confirm("确定要回收这 " + n + " 位用户的所有权限吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(async () => {
                let userIds = ''
                for(let i = 0; i < this.grantObj.users.length; i++)
                    userIds += (this.grantObj.users[i].id + ',')

                let r = await accountReq.revokeAll({userIds: userIds})
                if (r.code === 0) {
                    this.$message.success("操作成功");
                    await this.loadPageData()
                } else {
                    this.$message.error(r.msg);
                }
            }).catch(err => {
            });

        },
        async loadPageData(pageNo, pageSize, searchVal = null) {
            pageNo = pageNo ? pageNo : this.accountPage.curPageNo
            pageSize = pageSize ? pageSize : this.accountPage.pageSize
            let res = await accountReq.listPage({page: pageNo, limit: pageSize, searchVal: searchVal})
            if (res.code === 0) {
                this.accountTableData = res.data
                this.accountPage.total = res.count
            } else {
                this.initAccountPage()
                this.$message.error(res.msg)
            }
        }
    },
    mounted() {
        // 加载列表
        this.loadPageData(this.accountPage.curPageNo, this.accountPage.pageSize)
    },
    data() {
        return {
            accountTableData: [],
            accountPage: {
                curPageNo: 1,
                pageSize: 10,
                total: 0,
            },
            accForm: {show: false, event: '', data: null},
            grantObj: {show: false, users: []},
            filterVal: null
        };
    },
}
</script>

<style lang="scss">
.account-table-toolbar {
    .el-input {
        width: 330px;
    }

    .el-button-group {
        margin-left: 15px;
    }
}

</style>